package com.zhuhjay.boot.config;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.spring.AnnotationBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Objects;

/**
 * 2.0.1版本SpringBoot 使用构造器注入会抛出异常？
 * 试了很久的 @ConfigurationProperties 一直注入失败
 * 索性尝试 EnvironmentAware 来获取环境变量, 麻了
 * @author ZhuHJay
 * @date 2022/4/1 21:24
 */
@Configuration
public class CustomDubboConfiguration implements EnvironmentAware {

    private String applicationName;
    private String registryAddress;
    private String protocolName;
    private Integer protocolPort;
    private String packageScan;

    @Bean
    public ApplicationConfig applicationConfig(){
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName(applicationName);
        return applicationConfig;
    }

    @Bean
    public RegistryConfig registryConfig(){
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress(registryAddress);
        return registryConfig;
    }

    @Bean
    public ProtocolConfig consumerConfig(){
        ProtocolConfig protocolConfig = new ProtocolConfig();
        // 只能设置 dubbo 协议名称
        protocolConfig.setName(protocolName);
        protocolConfig.setPort(protocolPort);
        return protocolConfig;
    }

    @Bean
    public AnnotationBean annotationBean(){
        AnnotationBean annotationBean = new AnnotationBean();
        annotationBean.setPackage(packageScan);
        return annotationBean;
    }

    @Override
    public void setEnvironment(Environment environment) {
        // 使用容器内置组件来进行环境变量的获取
        applicationName = environment.getProperty("custom.dubbo.application-name");
        registryAddress = environment.getProperty("custom.dubbo.registry-address");
        protocolName = environment.getProperty("custom.dubbo.protocol-name");
        protocolPort = Integer.parseInt(Objects.requireNonNull(environment.getProperty("custom.dubbo.protocol-port")));
        packageScan = environment.getProperty("custom.dubbo.package-scan");
    }
}
